#!/usr/bin/env python3
import sys
import pexpect
import json
import argparse as paser
import os

SUBFIX = 'xin'


def connect(cmd, pwd):
    child = pexpect.spawn(cmd)
    i = child.expect(['.*password.*', '.*continue.*?', pexpect.EOF, pexpect.TIMEOUT])
    if i == 0:
        child.sendline("{}".format(pwd))
        child.interact()
    elif i == 1:
        child.sendline("yes")
        child.sendline("{}".format(pwd))
        child.interact()
    else:
        print('connect fail')

    print('\033[92mgoodbye ~\033[0m')


if __name__ == '__main__':
    argpaser = paser.ArgumentParser(description='命令行ssh自动登录')
    argpaser.add_argument('-d', '--domain', help='主机名')
    args = argpaser.parse_args()
    selfPath = sys.argv[0]
    selfFullPath = selfPath if not os.path.islink(selfPath) else os.readlink(selfPath)
    configPath = os.path.abspath(selfFullPath + '/../../config/login.json')
    with open(configPath) as configFile:
        configs = json.load(configFile)
    if args.domain not in configs:
        print('配置文件未定义该主机')
        exit()

    config = configs.get(args.domain)
    connect('ssh root@{} -p {}'.format(config['host'], config['port']), config['pwd'].replace(SUBFIX, ''))
